<script setup>
import { ref, onMounted } from 'vue'
import { Edit, Delete, Plus, Star, StarFilled, Collection, CollectionTag } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  lessonCategoryListService, 
  lessonListService, 
  lessonAddService, 
  lessonDeleteService, 
  myLessonListService, 
  lessonUpdateService,
  lessonLikeService,
  lessonUnlikeService,
  lessonFavoriteService,
  lessonUnfavoriteService,
  getLessonLikeStatusService,
  getLessonFavoriteStatusService,
  getLessonLikeCountService,
  getLessonFavoriteCountService,
  getUserFavoritesService,
  getRecommendedLessonsService
} from '@/api/lesson.js'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import useUserInfoStore from '@/stores/userInfo.js'
import { userService } from '@/api/user.js'

// 导入 token
import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore()

// 导入用户信息store
const userInfoStore = useUserInfoStore()

// 标签页
const activeTab = ref('my')

// 表单引用
const formRef = ref(null)

// 课程分类数据模型
const categorys = ref([])
// 用户搜索时选中的分类id
const categoryId = ref('')
// 用户输入的模糊查询关键字
const keyword = ref('')

// 文章列表数据模型
const lessons = ref([])
// 分页条数据模型
const currentPage = ref(1) // 当前页
const pageSize = ref(3) // 每页条数
const total = ref(20) // 总条数

// 搜索课程列表
const lessonList = async () => {
  let params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    categoryId: categoryId.value ? categoryId.value : null,
    keyword: keyword.value ? keyword.value : '',
    userId: activeTab.value === 'my' ? userInfoStore.info.id : null  // 根据标签页决定是否传userId
  }
  let result = await myLessonListService(params)
  total.value = result.data.total
  lessons.value = result.data.items
  
  // 处理数据, 给数据模型扩展一个属性 categoryName, 分类名称
  for (let i = 0; i < lessons.value.length; i++) {
    let lesson = lessons.value[i]
    for (let j = 0; j < categorys.value.length; j++) {
      if (lesson.categoryId == categorys.value[j].id) {
        lesson.categoryName = categorys.value[j].categoryName
      }
    }
  }
}

// 获取课程分类列表
const lessonCategoryList = async () => {
  try {
    let result = await lessonCategoryListService()
    if (result.code === 0) {
      categorys.value = result.data
    } else {
      ElMessage.error(result.msg || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取课程列表数据
lessonCategoryList()
lessonList()

// 组件挂载时，根据当前标签页加载相应数据
onMounted(() => {
  if (activeTab.value === 'favorites') {
    fetchFavorites()
  } else if (activeTab.value === 'recommended') {
    fetchRecommendations()
  } else {
    lessonList()
  }
})

// 控制抽屉是否显示
const visibleDrawer = ref(false)

// 添加表单数据模型
const lessonModel = ref({
  title: '',
  categoryId: '',
  coverImg: '',
  videoUrl: '',
  content: '',
  state: ''
})

// 上传成功的回调函数 - 封面图片
const uploadSuccess = (result) => {
  if (result.code === 0) {
    lessonModel.value.coverImg = result.data
    ElMessage.success('封面图片上传成功')
  } else {
    ElMessage.error(result.msg || '封面图片上传失败')
  }
}

// 上传前的验证
const beforeVideoUpload = (file) => {
  const isVideo = file.type.startsWith('video/')
  const isLt100M = file.size / 1024 / 1024 < 100

  if (!isVideo) {
    ElMessage.error('只能上传视频文件！')
    return false
  }
  if (!isLt100M) {
    ElMessage.error('视频大小不能超过 100MB!')
    return false
  }
  return true
}

// 上传成功的回调函数 - 视频
const uploadVideoSuccess = (result) => {
  if (result.code === 0) {
    lessonModel.value.videoUrl = result.data
    ElMessage.success('视频上传成功')
  } else {
    ElMessage.error(result.msg || '视频上传失败')
  }
}

// 上传失败的回调函数
const uploadError = (error) => {
  ElMessage.error('上传失败：' + (error.message || '未知错误'))
}

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入课程标题', trigger: 'blur' },
    { min: 1, max: 15, message: '长度在1到15个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (!Number.isInteger(Number(value))) {
          callback(new Error('课程分类ID必须是数字'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  coverImg: [
    { required: true, message: '请上传课程封面', trigger: 'blur' }
  ],
  videoUrl: [
    { required: true, message: '请上传课程视频', trigger: 'blur' }
  ],
  content: [
    { 
      required: true, 
      message: '请输入课程内容', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '' || value === '<p><br></p>') {
          callback(new Error('请输入课程内容'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 添加编辑器事件处理函数
const onEditorReady = (quill) => {
  console.log('编辑器已准备就绪')
  // 初始化编辑器内容
  if (!lessonModel.value.content) {
    lessonModel.value.content = ''
  }
  console.log('初始化内容:', lessonModel.value.content)
}

const onEditorTextChange = ({ html, text }) => {
  if (html !== undefined) {
    lessonModel.value.content = html
    console.log('内容已更改:', html)
  }
}

// 添加课程
const addLesson = async (clickState) => {
  try {
    // 准备提交的数据
    const submitData = {
      ...lessonModel.value,
      state: clickState,
      categoryId: parseInt(lessonModel.value.categoryId)
    }

    // 验证表单数据
    if (!submitData.title?.trim()) {
      ElMessage.error('请输入课程标题')
      return
    }

    if (!submitData.categoryId) {
      ElMessage.error('请选择课程分类')
      return
    }

    if (!submitData.coverImg) {
      ElMessage.error('请上传课程封面')
      return
    }

    if (!submitData.videoUrl) {
      ElMessage.error('请上传课程视频')
      return
    }

    if (!submitData.content || submitData.content.trim() === '' || submitData.content === '<p><br></p>') {
      ElMessage.error('请输入课程内容')
      return
    }

    // 调用添加API
    const result = await lessonAddService(submitData)
    
    if (result.code === 0) {
      ElMessage.success('课程添加成功')
      visibleDrawer.value = false
      lessonList()
      clearForm()
    } else {
      ElMessage.error(result.msg || '添加失败')
    }
  } catch (error) {
    console.error('添加失败，详细错误:', error)
    console.error('错误响应数据:', error.response?.data)
    const errorMessage = error.response?.data?.msg || error.message || '添加失败，请稍后重试'
    ElMessage.error(errorMessage)
  }
}

// 清空表单
const clearForm = () => {
  lessonModel.value = {
    title: '',
    categoryId: '',
    coverImg: '',
    videoUrl: '',
    content: '',
    state: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 分页改变时的处理函数
const onSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1 // 切换每页条数时，重置为第一页
  lessonList()
}

const onCurrentChange = (newPage) => {
  currentPage.value = newPage
  lessonList()
}

// 打开抽屉时，确保已加载分类数据
const openDrawer = async () => {
  try {
    // 无论是否为空都重新获取一次，确保数据最新
    const result = await lessonCategoryListService()
    if (result.code === 0) {
      categorys.value = result.data
      if (categorys.value.length === 0) {
        ElMessage.warning('暂无课程分类，请先添加课程分类')
        return
      }
      visibleDrawer.value = true
      // 清空表单数据
      clearForm()
    } else {
      ElMessage.error(result.msg || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 检查是否为课程创建者
const isCreator = (lesson) => {
  return lesson.createUser === userInfoStore.info.id
}

// 处理编辑和删除操作的错误
const handleOperationError = (error) => {
  console.error('操作失败:', error)
  const errorMessage = error.response?.data?.msg || error.message || '操作失败'
  ElMessage.error(errorMessage)
}

// 删除课程
const deleteLesson = (row) => {
  if (!isCreator(row)) {
    ElMessage.error('无权删除他人的课程')
    return
  }

  ElMessageBox.confirm(
    '确认删除该课程吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const result = await lessonDeleteService(row.id)
      if (result.code === 0) {
        ElMessage.success('删除成功')
        lessonList()
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      handleOperationError(error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 编辑课程
const editLesson = (row) => {
  if (!isCreator(row)) {
    ElMessage.error('无权修改他人的课程')
    return
  }
  
  // 确保数据类型正确
  lessonModel.value = {
    ...row,
    id: parseInt(row.id),
    categoryId: parseInt(row.categoryId),
    createUser: parseInt(row.createUser)
  }
  
  console.log('编辑课程数据:', lessonModel.value)
  visibleDrawer.value = true
}

// 提交编辑
const submitEdit = async (clickState) => {
  try {
    // 准备提交的数据
    const submitData = {
      ...lessonModel.value,
      state: clickState,
      id: parseInt(lessonModel.value.id),
      categoryId: parseInt(lessonModel.value.categoryId)
    }

    // 验证表单数据
    if (!submitData.title?.trim()) {
      ElMessage.error('请输入课程标题')
      return
    }

    if (!submitData.categoryId) {
      ElMessage.error('请选择课程分类')
      return
    }

    if (!submitData.coverImg) {
      ElMessage.error('请上传课程封面')
      return
    }

    if (!submitData.videoUrl) {
      ElMessage.error('请上传课程视频')
      return
    }

    if (!submitData.content || submitData.content.trim() === '' || submitData.content === '<p><br></p>') {
      ElMessage.error('请输入课程内容')
      return
    }

    // 调用更新API
    const result = await lessonUpdateService(submitData)
    
    if (result.code === 0) {
      ElMessage.success('课程更新成功')
      visibleDrawer.value = false
      lessonList()
      clearForm()
    } else {
      ElMessage.error(result.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新失败，详细错误:', error)
    console.error('错误响应数据:', error.response?.data)
    const errorMessage = error.response?.data?.msg || error.message || '更新失败，请稍后重试'
    ElMessage.error(errorMessage)
  }
}

// Quill编辑器配置
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'align': [] }],
      ['link', 'image'],
      ['clean']
    ]
  },
  placeholder: '请输入课程内容...'
}

// 重置搜索条件
const resetSearch = () => {
  categoryId.value = ''
  keyword.value = ''
  lessonList()
}

// 收藏列表数据
const favorites = ref([])
const loadingFavorites = ref(false)

// 获取收藏列表
const fetchFavorites = async () => {
  if (activeTab.value !== 'favorites') return
  
  loadingFavorites.value = true
  try {
    const res = await getUserFavoritesService()
    if (res.code === 0) {
      favorites.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取收藏列表失败')
    }
  } catch (error) {
    console.error('获取收藏列表出错:', error)
    ElMessage.error('获取收藏列表失败，请稍后重试')
  } finally {
    loadingFavorites.value = false
  }
}

// 处理标签页切换
const handleTabClick = () => {
  currentPage.value = 1
  resetSearch()
  
  if (activeTab.value === 'favorites') {
    fetchFavorites()
  } else if (activeTab.value === 'recommended') {
    fetchRecommendations()
  } else {
    lessonList()
  }
}

// 控制课程详情对话框的显示
const dialogVisible = ref(false)
// 当前选中的课程
const currentLesson = ref(null)

// 点赞和收藏状态
const isLiked = ref(false)
const isFavorited = ref(false)
const likeCount = ref(0)
const favoriteCount = ref(0)

// 显示课程详情
const showLessonDetail = async (lesson) => {
  currentLesson.value = lesson
  dialogVisible.value = true
  
  // 获取点赞和收藏状态
  await getLikeStatus(lesson.id)
  await getFavoriteStatus(lesson.id)
  
  // 获取点赞和收藏数量
  await getLikeCount(lesson.id)
  await getFavoriteCount(lesson.id)
}

// 获取点赞状态
const getLikeStatus = async (lessonId) => {
  try {
    const result = await getLessonLikeStatusService(lessonId)
    if (result.code === 0) {
      isLiked.value = result.data
    }
  } catch (error) {
    console.error('获取点赞状态失败:', error)
  }
}

// 获取收藏状态
const getFavoriteStatus = async (lessonId) => {
  try {
    const result = await getLessonFavoriteStatusService(lessonId)
    if (result.code === 0) {
      isFavorited.value = result.data
    }
  } catch (error) {
    console.error('获取收藏状态失败:', error)
  }
}

// 获取点赞数量
const getLikeCount = async (lessonId) => {
  try {
    const result = await getLessonLikeCountService(lessonId)
    if (result.code === 0) {
      likeCount.value = result.data
    }
  } catch (error) {
    console.error('获取点赞数量失败:', error)
  }
}

// 获取收藏数量
const getFavoriteCount = async (lessonId) => {
  try {
    const result = await getLessonFavoriteCountService(lessonId)
    if (result.code === 0) {
      favoriteCount.value = result.data
    }
  } catch (error) {
    console.error('获取收藏数量失败:', error)
  }
}

// 点赞/取消点赞课程
const toggleLike = async () => {
  if (!currentLesson.value) return
  
  try {
    if (isLiked.value) {
      // 取消点赞
      const result = await lessonUnlikeService(currentLesson.value.id)
      if (result.code === 0) {
        isLiked.value = false
        likeCount.value = Math.max(0, likeCount.value - 1)
        ElMessage.success('取消点赞成功')
      } else {
        ElMessage.error(result.msg || '取消点赞失败')
      }
    } else {
      // 点赞
      const result = await lessonLikeService(currentLesson.value.id)
      if (result.code === 0) {
        isLiked.value = true
        likeCount.value += 1
        ElMessage.success('点赞成功')
      } else {
        ElMessage.error(result.msg || '点赞失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 收藏/取消收藏课程
const toggleFavorite = async () => {
  if (!currentLesson.value) return
  
  try {
    if (isFavorited.value) {
      // 取消收藏
      const result = await lessonUnfavoriteService(currentLesson.value.id)
      if (result.code === 0) {
        isFavorited.value = false
        favoriteCount.value = Math.max(0, favoriteCount.value - 1)
        ElMessage.success('取消收藏成功')
        
        // 如果当前是收藏标签页，刷新收藏列表
        if (activeTab.value === 'favorites') {
          fetchFavorites()
        }
      } else {
        ElMessage.error(result.msg || '取消收藏失败')
      }
    } else {
      // 收藏
      const result = await lessonFavoriteService(currentLesson.value.id)
      if (result.code === 0) {
        isFavorited.value = true
        favoriteCount.value += 1
        ElMessage.success('收藏成功')
      } else {
        ElMessage.error(result.msg || '收藏失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

import Comment from '@/components/Comment.vue'

// 在setup中添加
const recommendedLessons = ref([])
const loadingRecommendations = ref(false)

// 获取推荐课程
const fetchRecommendations = async () => {
  loadingRecommendations.value = true
  try {
    const res = await getRecommendedLessonsService()
    if (res.code === 0) {
      recommendedLessons.value = res.data
    } else {
      ElMessage.error(res.msg || '获取推荐课程失败')
    }
  } catch (error) {
    console.error('获取推荐课程失败:', error)
    ElMessage.error('获取推荐课程失败')
  } finally {
    loadingRecommendations.value = false
  }
}
</script>

<template>
    <el-card class="page-container">
      <template #header>
        <div class="header">
          <span>课程管理</span>
          <div class="extra">
            <el-button v-if="activeTab === 'my' && tokenStore.userRole === 1" type="success" @click="openDrawer">添加课程</el-button>
          </div>
        </div>
      </template>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="我的课程" name="my">
          <!-- 搜索表单 -->
          <el-form inline class="search-form">
            <el-form-item label="课程分类：">
              <el-select placeholder="请选择" v-model="categoryId" style="width: 200px">
                <el-option 
                  v-for="c in categorys" 
                  :key="c.id" 
                  :label="c.categoryName"
                  :value="c.id">
                </el-option>
              </el-select>
            </el-form-item>
      
            <el-form-item label="搜索：">
              <el-input v-model="keyword" placeholder="请输入搜索关键词" style="width: 200px"></el-input>
            </el-form-item>
      
            <el-form-item>
              <el-button type="primary" @click="lessonList">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 课程卡片列表 -->
          <div class="lesson-grid">
            <el-card 
              v-for="lesson in lessons" 
              :key="lesson.id" 
              class="lesson-card"
              @click="showLessonDetail(lesson)"
            >
              <div class="lesson-cover">
                <img :src="lesson.coverImg" :alt="lesson.title">
                <div class="lesson-state" :class="lesson.state === '已发布' ? 'published' : 'draft'">
                  {{ lesson.state }}
                </div>
              </div>
              <div class="lesson-info">
                <h3 class="lesson-title">{{ lesson.title }}</h3>
                <div class="lesson-meta">
                  <span>{{ lesson.categoryName }}</span>
                  <span>{{ lesson.createUserName }}</span>
                </div>
                <div class="lesson-stats">
                  <span class="stat-item">
                    <el-icon><Collection /></el-icon>
                    {{ lesson.likeCount || 0 }}
                  </span>
                  <span class="stat-item">
                    <el-icon><Star /></el-icon>
                    {{ lesson.favoriteCount || 0 }}
                  </span>
                </div>
              </div>
              <div v-if="activeTab === 'my' && isCreator(lesson)" class="lesson-actions">
                <el-button :icon="Edit" circle plain type="primary" @click.stop="editLesson(lesson)"></el-button>
                <el-button :icon="Delete" circle plain type="danger" @click.stop="deleteLesson(lesson)"></el-button>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="已发布课程" name="published">
          <!-- 搜索表单 -->
          <el-form inline class="search-form">
            <el-form-item label="课程分类：">
              <el-select placeholder="请选择" v-model="categoryId" style="width: 200px">
                <el-option 
                  v-for="c in categorys" 
                  :key="c.id" 
                  :label="c.categoryName"
                  :value="c.id">
                </el-option>
              </el-select>
            </el-form-item>
      
            <el-form-item label="搜索：">
              <el-input v-model="keyword" placeholder="请输入搜索关键词" style="width: 200px"></el-input>
            </el-form-item>
      
            <el-form-item>
              <el-button type="primary" @click="lessonList">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 课程卡片列表 -->
          <div class="lesson-grid">
            <el-card 
              v-for="lesson in lessons" 
              :key="lesson.id" 
              class="lesson-card"
              @click="showLessonDetail(lesson)"
            >
              <div class="lesson-cover">
                <img :src="lesson.coverImg" :alt="lesson.title">
                <div class="lesson-state published">已发布</div>
              </div>
              <div class="lesson-info">
                <h3 class="lesson-title">{{ lesson.title }}</h3>
                <div class="lesson-meta">
                  <span>{{ lesson.categoryName }}</span>
                  <span>{{ lesson.createUserName }}</span>
                </div>
                <div class="lesson-stats">
                  <span class="stat-item">
                    <el-icon><Collection /></el-icon>
                    {{ lesson.likeCount || 0 }}
                  </span>
                  <span class="stat-item">
                    <el-icon><Star /></el-icon>
                    {{ lesson.favoriteCount || 0 }}
                  </span>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="我的收藏" name="favorites">
          <div v-if="loadingFavorites" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          
          <div v-else-if="favorites.length === 0" class="empty-container">
            <el-empty description="暂无收藏的课程" />
            <el-button type="primary" @click="activeTab = 'published'">去浏览课程</el-button>
          </div>
          
          <div v-else class="lesson-grid">
            <el-card 
              v-for="lesson in favorites" 
              :key="lesson.id" 
              class="lesson-card"
              @click="showLessonDetail(lesson)"
            >
              <div class="lesson-cover">
                <img :src="lesson.coverImg" :alt="lesson.title">
                <div class="lesson-state published">已发布</div>
              </div>
              <div class="lesson-info">
                <h3 class="lesson-title">{{ lesson.title }}</h3>
                <div class="lesson-meta">
                  <span>{{ lesson.categoryName }}</span>
                  <span>{{ lesson.createUserName }}</span>
                </div>
                <div class="lesson-stats">
                  <span class="stat-item">
                    <el-icon><Collection /></el-icon>
                    {{ lesson.likeCount || 0 }}
                  </span>
                  <span class="stat-item">
                    <el-icon><Star /></el-icon>
                    {{ lesson.favoriteCount || 0 }}
                  </span>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="推荐课程" name="recommended">
          <div v-if="loadingRecommendations" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          
          <div v-else-if="recommendedLessons.length === 0" class="empty-container">
            <el-empty description="暂无推荐课程" />
            <el-button type="primary" @click="activeTab = 'published'">去浏览课程</el-button>
          </div>
          
          <div v-else class="lesson-grid">
            <el-card 
              v-for="lesson in recommendedLessons" 
              :key="lesson.id" 
              class="lesson-card"
              @click="showLessonDetail(lesson)"
            >
              <div class="lesson-cover">
                <img :src="lesson.coverImg" :alt="lesson.title">
                <div class="lesson-state published">已发布</div>
              </div>
              <div class="lesson-info">
                <h3 class="lesson-title">{{ lesson.title }}</h3>
                <div class="lesson-meta">
                  <span>{{ lesson.categoryName }}</span>
                  <span>{{ lesson.createUserName }}</span>
                </div>
                <div class="lesson-stats">
                  <span class="stat-item">
                    <el-icon><Collection /></el-icon>
                    {{ lesson.likeCount || 0 }}
                  </span>
                  <span class="stat-item">
                    <el-icon><Star /></el-icon>
                    {{ lesson.favoriteCount || 0 }}
                  </span>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <!-- 分页条 -->
      <el-pagination 
        v-model="currentPage"
        :page-size="pageSize"
        :page-sizes="[8, 12, 16, 20]"
        layout="jumper, total, sizes, prev, pager, next" 
        background 
        :total="total" 
        @size-change="onSizeChange"
        @current-change="onCurrentChange" 
        style="margin-top: 20px; justify-content: flex-end" />
  
      <!-- 课程详情对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="课程详情"
        width="70%"
        :destroy-on-close="true"
      >
        <template v-if="currentLesson">
          <div class="lesson-detail">
            <h2>{{ currentLesson.title }}</h2>
            <div class="detail-meta">
              <span>分类：{{ currentLesson.categoryName }}</span>
              <span>作者：{{ currentLesson.createUserName }}</span>
              <span>发布时间：{{ currentLesson.createTime }}</span>
              <span>状态：{{ currentLesson.state }}</span>
            </div>
            <div class="detail-actions">
              <el-button 
                :icon="isLiked ? CollectionTag : Collection" 
                :type="isLiked ? 'primary' : 'default'"
                @click.stop="toggleLike">
                {{ isLiked ? '已点赞' : '点赞' }} ({{ likeCount }})
              </el-button>
              <el-button 
                :icon="isFavorited ? StarFilled : Star" 
                :type="isFavorited ? 'warning' : 'default'"
                @click.stop="toggleFavorite">
                {{ isFavorited ? '已收藏' : '收藏' }} ({{ favoriteCount }})
              </el-button>
            </div>
            <div class="detail-video">
              <video 
                v-if="currentLesson.videoUrl" 
                :src="currentLesson.videoUrl" 
                controls
                preload="metadata"
                style="width: 100%; max-height: 400px;">
                您的浏览器不支持视频播放
              </video>
            </div>
            <div class="detail-content" v-html="currentLesson.content"></div>
            <Comment :lessonId="currentLesson.id" />
          </div>
        </template>
      </el-dialog>

      <!-- 抽屉 -->
      <el-drawer v-model="visibleDrawer" title="添加课程" direction="rtl" size="50%">
        <!-- 添加课程表单 -->
        <el-form ref="formRef" :model="lessonModel" :rules="rules" label-width="100px">
          <el-form-item label="课程标题" prop="title">
            <el-input v-model="lessonModel.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="课程分类" prop="categoryId">
            <el-select v-model="lessonModel.categoryId" placeholder="请选择分类">
              <el-option
                v-for="item in categorys"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程封面" prop="coverImg">
            <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="uploadSuccess">
              <img v-if="lessonModel.coverImg" :src="lessonModel.coverImg" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="课程视频" prop="videoUrl">
            <el-upload
              class="video-uploader"
              :auto-upload="true"
              :show-file-list="false"
              action="/api/upload"
              name="file"
              :headers="{'Authorization': tokenStore.token}"
              :on-success="uploadVideoSuccess"
              :before-upload="beforeVideoUpload"
              :on-error="uploadError"
              accept="video/*">
              <video v-if="lessonModel.videoUrl" 
                     :src="lessonModel.videoUrl" 
                     controls
                     preload="metadata"
                     class="video-preview">
                您的浏览器不支持视频播放
              </video>
              <el-icon v-else class="video-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="课程内容" prop="content">
            <div class="editor">
              <quill-editor
                :content="lessonModel.content"
                @update:content="lessonModel.content = $event"
                :options="editorOptions"
                @ready="onEditorReady"
                @text-change="onEditorTextChange"
                contentType="html">
              </quill-editor>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="lessonModel.id ? submitEdit('已发布') : addLesson('已发布')">发布</el-button>
            <el-button type="info" @click="lessonModel.id ? submitEdit('草稿') : addLesson('草稿')">草稿</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
    </el-card>
  </template>
  

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.search-form {
  margin-bottom: 20px;
}

.lesson-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.lesson-card {
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  position: relative;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }

  .lesson-cover {
    position: relative;
    height: 160px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .lesson-state {
      position: absolute;
      top: 10px;
      right: 10px;
      padding: 2px 8px;
      border-radius: 4px;
      font-size: 12px;
      color: white;

      &.published {
        background-color: #67c23a;
      }

      &.draft {
        background-color: #909399;
      }
    }
  }

  .lesson-info {
    padding: 12px;

    .lesson-title {
      margin: 0 0 8px;
      font-size: 16px;
      font-weight: bold;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .lesson-meta {
      display: flex;
      justify-content: space-between;
      color: #666;
      font-size: 12px;
    }

    .lesson-stats {
      display: flex;
      justify-content: space-between;
      color: #666;
      font-size: 12px;
      margin-top: 8px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }

  .lesson-actions {
    position: absolute;
    bottom: 12px;
    right: 12px;
    display: none;
  }

  &:hover .lesson-actions {
    display: flex;
    gap: 8px;
  }
}

.lesson-detail {
  h2 {
    margin-bottom: 20px;
    color: #303133;
  }

  .detail-meta {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    color: #666;
    font-size: 14px;
  }

  .detail-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    
    .el-button {
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
  }

  .detail-video {
    margin-bottom: 20px;
    background: #f5f5f5;
    border-radius: 4px;
    overflow: hidden;
  }

  .detail-content {
    line-height: 1.6;
    color: #303133;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.video-uploader {
  :deep {
    .video-preview {
      width: 320px;
      height: 180px;
      display: block;
      object-fit: contain;
      background: #f0f0f0;
      margin-bottom: 8px;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      width: 320px;
      height: 180px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .video-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.loading-container {
  padding: 20px 0;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  
  .el-button {
    margin-top: 20px;
  }
}

.detail-comments {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}
</style>
